package com.doge.walknovel.business.reader

import android.animation.*
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import com.doge.wnpro.databinding.LayoutReaderGuideBinding
import com.doge.walknovel.utils.setOnClickCallback
import com.doge.walknovel.utils.spReadBoolean
import com.doge.walknovel.utils.spWrite

class ReaderGuideLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
    private val binding =
        LayoutReaderGuideBinding.inflate(LayoutInflater.from(context), this)
    private var animator: AnimatorSet? = null
    private val key = "guideCenterMenu"
    private val folder = "reader"
    private val firstTimeUsing: Boolean get() = spReadBoolean(key, true, folder)
    private fun setUsed() = spWrite(key, false, folder)
    private var callback: OnClickListener? = null

    init {
        val flag = firstTimeUsing
        isVisible = flag
        if (flag) {
            alpha = 0f
            animate().alpha(1f).setStartDelay(500).setDuration(500).start()
        }

        binding.center.setOnClickCallback {
            setUsed()
            callback?.onClick(this)
            binding.center.setOnClickListener(null)
            animate().alpha(0f).setDuration(250)
                .setListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator?) {
                        isVisible = false
                    }
                }).start()
        }
    }

    override fun setOnClickListener(l: OnClickListener?) {
        callback = l
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        animator?.cancel()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        animScaleInfinite()
    }

    private fun animScaleInfinite() {
        animator?.cancel()
        animator = AnimatorSet()
        val scaleX = ObjectAnimator.ofFloat(binding.tip1, "scaleX", 1f, 1.2f, 1f)
        val scaleY = ObjectAnimator.ofFloat(binding.tip1, "scaleY", 1f, 1.2f, 1f)
        scaleX.repeatCount = ValueAnimator.INFINITE
        scaleY.repeatCount = ValueAnimator.INFINITE
        animator?.duration = 1000
        animator?.play(scaleX)?.with(scaleY)
        animator?.start()
    }
}